import argparse
import io
import os
import shutil
import re
from dataclasses import replace

import requests
from PIL import Image

# key为url，value为相对路径
img_dict = {}


def start():
    # 当前文件夹内md个数计算
    folder_path = "files"
    folder_path = os.path.abspath(folder_path)
    folder_path = r"E:\上课资料\华测教育\鸿蒙课件语雀下载的md文档"
    print(f"folder_path: {folder_path}")
    file_list = os.listdir(folder_path)
    print(f"file_list: {file_list}")
    output_path = os.path.join(folder_path, "output")
    for item in file_list:
        if item[-3:] == '.md':
            print(f"file: {item}")
            md_file_path = os.path.join(folder_path, item)
            replace_url_to_relative_path(md_file_path, output_path)


def replace_url_to_relative_path(file_path, output_path):
    output_path = os.path.join(output_path, os.path.basename(file_path))
    output_path = output_path.replace(".md", "")

    # 创建目录
    assert_folder = output_path + ".assert"
    if not os.path.exists(assert_folder):
        os.makedirs(assert_folder)

    print(f"output_path： {output_path}")
    with open(file_path, "r+", encoding="utf-8") as file:
        content = file.read()
        # 提取所有的图片地址
        img_urls = re.findall(r'!\[.*?\]\((.*?)\)', content)
        print(f"img_url: {img_urls}")
        for item in img_urls:
            relative_path = os.path.basename(assert_folder)
            relative_path = os.path.join(relative_path, item.split('/')[-1])
            print(f"relative_path: {relative_path}")
            # 保存到字典
            # img_dict[item] = relative_path
            # print(f"img_dict: {img_dict}")
            content = content.replace(item, str(relative_path))
            down_image(item, assert_folder)

        # print(f"content: {content}")
        # for k, v in img_dict:
        #     content.replace(k, v)
        # file.seek(0)
        output_file = open(output_path + ".md", "w", encoding="utf-8")
        output_file.write(content)

# 下载图片
def down_image(img_url, save_folder):
    print(f"正在处理 {img_url}")
    response = requests.get(img_url)
    if response.status_code == 200:
        img = Image.open(io.BytesIO(response.content))
        img_name = os.path.join(save_folder, img_url.split('/')[-1])
        img.save(img_name)
    else:
        print("下载图片失败，错误代码：", response.status_code)


# 将url替换为相对路径
# def replace_url_to_relative_path(file_path, content):
#     with open(file_path, "w", encoding="utf-8") as file:
#         # content = file.read()
#         for k, v in img_dict:
#             content.replace(k, v)
#         file.write(content)


start()

# # 添加命令行参数
# parser = argparse.ArgumentParser()
# if count_md == 1:
#     parser.add_argument('--input', type=str, default=md_file, help='markdown file')
# else:
#     parser.add_argument('--input', type=str, help='markdown file')
# parser.add_argument('--imgdir', type=str, default='img', help='存图片文件夹')
# parser.add_argument('--output', type=str, help='输出md文件名')
# args = parser.parse_args()
# imgdir = args.imgdir
# mdout = 'mdout'  # 输出内容所在文件夹
# print(f"输入文件: {args.input} 图片文件夹: {args.imgdir} 输出文件: {args.output}")
# if args.output == None:  # 没有规定输出md文件名，则默认用原文件名
#     args.output = os.path.join(mdout, os.path.basename(args.input))
#
# print(f"输入文件: {args.input} 图片文件夹: {args.imgdir} 输出文件: {args.output}")
# # 文件夹创建
# if not os.path.exists(mdout):
#     os.makedirs(mdout)
# if not os.path.exists(os.path.join(mdout, imgdir)):
#     os.makedirs(os.path.join(mdout, imgdir))
# with open(args.input, 'r', encoding='utf-8') as f:
#     md = f.read()
# # 正则提取
# img_md = re.findall(r'!\[.*?\]\((.*?)\)', md)
# img_html = re.findall(r'<img src="(.*?)" .*?/>', md)
# img_paths = img_md + img_html
#
# for i in img_paths:
#     img = os.path.join(imgdir, os.path.basename(i))
#     shutil.copy(i, os.path.join(mdout, img))
#     md = md.replace(i, img)
#
# with open(args.output, 'w', encoding='utf-8') as f:
#     f.write(md)
